package com.teach.config.interceptors;

import cn.hutool.core.util.StrUtil;
import com.teach.AuthUser;

import com.teach.config.ConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**<pre>
 * jwt处理拦截器
 * - 获取请求头或者请求参数中的x-token的jwt字符串
 * - 将jwt字符串转换成AuthUser对象
 * - 设置AuthUser对象
 * Class: com.teach.config.interceptors.JWTInterceptor
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 * @author J.L.Zhou
 * @since 2022年10月22日 下午2:14:31
 * @version 1.0
 */
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {


  @Autowired
  private com.teach.util.JwtUtil jwtUtil;
  @Autowired
  private ConfigProperties config;


  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String jwt = request.getHeader(config.getJwt().getTokenName());
    if(StrUtil.isBlank(jwt)) {
      jwt = request.getParameter(config.getJwt().getTokenName());
    }
    log.trace("jwt:{}",jwt);
    if(StrUtil.isBlank(jwt)){
      return true;
    }

    jwtUtil.verify(jwt);
    AuthUser user = jwtUtil.parse(jwt, AuthUser.class);
    AuthUser.set(user);
    return true;
  }

}
